<template>
    <div class="flexWrap upload__view">
        <img class="img" :src="src || 'http://a.efeng.co/resource/images/default.png'" alt="">
        <div style="width:calc(100% - 150px)">
            <div class="pr mt-10">
                <input type="file" class="pa" style="opacity: 0;" id="file" @change="uploadImg" />
                <el-button size="mini" type="primary">点击上传</el-button>
            </div>
            <div class="tip">{{tip}}</div>
        </div>
    </div>
</template>
<script>
import request from "@/utils/request";
export default {
    name: "upload",
    props: {
        src: {
            type: String,
        },
        limit: {
            type: Number,
        },
        tip: {
            type: String,
        },
        data: {
            type: Object //上传文件时带的参数，调用complete时也会返回
        },
        request: {
            type: Function
        },
        complete: {
            type:Function
        }
    },
    components: {

    },
    computed: {

    },
    data() {
        return {

        }
    },
    methods: {
        // 上传图片处理过程
        uploadImg(e) {
            if (!e || !e.target.files) {this.$message.error("请选择图片"); return}

            // 父组件自定义处理上传
            if (this.$listeners && this.$listeners.request) {
                this.$emit("request", {data:this.data, files: e.target.files});
                return;
            }

            let formData = new FormData()
            formData.append("file", e.target.files[0]);
            if (this.data) {
                for (let k in this.data) {
                    formData.append(k, this.data[k])
                }
            }

            (this.request || request).upload({
                url:"ads/upload.file", data: formData
            }).then( res => {
                this.$emit("complete", {...this.data, url: res.result.url});
            }, res => {
                this.$message.error("图片上传失败");
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.upload__view {
    .img {margin-right: 10px; padding: 5px; width: 60px; height: 60px; border-radius: 4px; border: 1px solid #f0f0f0; object-fit: contain}
    .tip {margin-top: 5px; font-size: 11px; color: #aaaaaa; line-height: 16px}
}
</style>
